<template>
  <view class="recharge-container">
    <!-- 渐变背景头部 -->
    <view class="header-gradient">
      <up-navbar :border="false" autoBack bgColor="transparent" leftIconColor="#fff" :title="useT('充值')" titleColor="#fff" placeholder />

      <!-- 充值金额输入卡片 -->
      <view class="amount-card">
        <view class="amount-label">{{ useT('充值金额') }}</view>
        <view class="amount-input-wrapper">
          <text class="currency-prefix">USDT</text>
          <input class="amount-input" type="digit" :placeholder="useT('0.00')" v-model="rechargeAmount" @input="onAmountInput" placeholder-class="amount-placeholder" />
        </view>
        <view class="quick-amounts">
          <view class="quick-amount-item" v-for="amount in quickAmounts" :key="amount" @click="selectQuickAmount(amount)">
            <text class="quick-amount-text">{{ amount }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 充值流程步骤 -->
      <view class="steps-flow">
        <view class="flow-item">
          <view class="flow-number">1</view>
          <text class="flow-text">{{ useT('输入金额') }}</text>
        </view>
        <view class="flow-arrow">→</view>
        <view class="flow-item">
          <view class="flow-number">2</view>
          <text class="flow-text">{{ useT('生成链接') }}</text>
        </view>
        <view class="flow-arrow">→</view>
        <view class="flow-item">
          <view class="flow-number">3</view>
          <text class="flow-text">{{ useT('DApp充值') }}</text>
        </view>
      </view>

      <!-- 钱包信息卡片 -->
      <view class="wallet-card" v-if="walletAddress">
        <view class="wallet-icon-wrapper">
          <view class="wallet-icon"></view>
        </view>
        <view class="wallet-info">
          <text class="wallet-label">{{ useT('收款地址') }}</text>
          <view class="wallet-address">
            <text class="address-text">{{ formatAddress(walletAddress) }}</text>
          </view>
        </view>
      </view>

      <!-- 充值链接卡片 -->
      <view class="link-card" v-if="rechargeUrl">
        <view class="link-success-badge">
          <view class="success-icon"></view>
          <text class="success-text">{{ useT('链接已生成') }}</text>
        </view>

        <!-- 二维码显示 -->
        <view class="qrcode-wrapper">
          <view class="qrcode-container">
            <canvas canvas-id="qrcode" id="qrcode" class="qrcode-canvas" :style="{ width: qrcodeSize + 'px', height: qrcodeSize + 'px' }" />
          </view>
          <text class="qrcode-tip">{{ useT('扫描二维码打开充值链接') }}</text>
        </view>

        <view class="link-url">
          <text class="url-text">{{ rechargeUrl }}</text>
        </view>
        <view class="link-actions">
          <button class="link-btn copy-btn" @click="copyUrl">
            <view class="btn-icon copy-icon"></view>
            <text class="link-btn-text">{{ useT('一键复制') }}</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { getRechargeConfig, updateUserInfo } from '@/api/user.js';
import { useUserStore } from '@/stores/user';
import { useT } from '@/utils/i18n.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
import CryptoJS from 'crypto-js';
import UQRCode from 'uqrcodejs';
import { nextTick, ref, watch } from 'vue';

// 获取用户store
const userStore = useUserStore();
// 响应式数据
const rechargeAmount = ref('100');
const rechargeUrl = ref('');
const walletAddress = ref('');

// 二维码尺寸(px)
const qrcodeSize = ref(160);

// 快捷金额选项
const quickAmounts = [1, 100, 500, 1000, 5000];

// 充值配置
const RECHARGE_CONFIG = {
  baseUrl: 'https://upay.x-verse.cn.lu/',
  // 默认钱包地址
  defaultAddress: '0xF1971D6a461DC7f63C0757812F62eA99e25f4Efe',
  // 默认用户ID
  defaultUserId: userStore.userInfo.uid,
  // 签名密钥(应该从服务器配置获取,这里仅作示例)
  secretKey: 'K7mP9xR2vN4qW8jL5tY1hB6nF3sD0gZ9cX7vM2kQ5wE8rT4yU1iO6pA3sD7fG0hJ'
};
// 监听金额变化,自动生成充值链接
watch(rechargeAmount, (newAmount) => {
  generateRechargeLink(newAmount);
});

onLoad(() => {
  // 页面加载时的初始化逻辑
});
// 页面显示时检查登录状态
onShow(async () => {
  uni.hideTabBar();
  if (userStore.isLoggedIn) {
    await updateUserInfo();
    const res = await getRechargeConfig();
    console.log('====>res', res);
    if (res.status === 200) {
      RECHARGE_CONFIG.defaultAddress = res.data.defaultAddress;
      RECHARGE_CONFIG.secretKey = res.data.secretKey;
      // 钱包地址
      walletAddress.value = RECHARGE_CONFIG.defaultAddress;
      // 如果有默认金额,生成链接和二维码
      if (rechargeAmount.value) {
        generateRechargeLink(rechargeAmount.value);
      }
    }
  }
});

// 从密钥中派生AES所需的key和iv,避免运行时生成随机数
const deriveAesKeyAndIv = (secretKey) => {
  const hash = CryptoJS.SHA256(secretKey).toString();
  const keyHex = hash.slice(0, 32);
  const ivHex = hash.slice(32, 64);
  return {
    key: CryptoJS.enc.Hex.parse(keyHex),
    iv: CryptoJS.enc.Hex.parse(ivHex)
  };
};

const AES_CTX = deriveAesKeyAndIv(RECHARGE_CONFIG.secretKey);

// 金额输入处理
const onAmountInput = (e) => {
  let value = e.detail.value;

  // 只允许数字和小数点
  value = value.replace(/[^\d.]/g, '');

  // 检测小数位数，如果超过2位就截断
  if (value.includes('.')) {
    const dotIndex = value.indexOf('.');
    const integerPart = value.substring(0, dotIndex);
    const decimalPart = value.substring(dotIndex + 1);

    // 移除小数部分中的其他小数点
    const cleanDecimal = decimalPart.replace(/\./g, '');

    // 如果小数位数超过2位，截断到2位
    if (cleanDecimal.length > 2) {
      value = `${integerPart}.${cleanDecimal.substring(0, 2)}`;
    } else {
      value = `${integerPart}.${cleanDecimal}`;
    }
  }

  // 使用 nextTick 确保值更新后重新渲染
  nextTick(() => {
    rechargeAmount.value = value;
  });
};

// 选择快捷金额
const selectQuickAmount = (amount) => {
  rechargeAmount.value = amount.toString();
};

// 格式化地址显示
const formatAddress = (address) => {
  if (!address || address.length < 12) return address;
  return `${address.slice(0, 6)}...${address.slice(-6)}`;
};

// 生成二维码
const generateQRCode = (url) => {
  nextTick(() => {
    const qr = new UQRCode();
    qr.data = url;
    qr.size = qrcodeSize.value;
    qr.make();

    const canvasContext = uni.createCanvasContext('qrcode');
    qr.canvasContext = canvasContext;
    qr.drawCanvas();
  });
};

// 复制链接
const copyUrl = () => {
  if (!rechargeUrl.value) {
    return;
  }

  uni.setClipboardData({
    data: rechargeUrl.value,
    success: () => {
      uni.showToast({
        title: useT('复制成功'),
        icon: 'success'
      });
    },
    fail: () => {
      uni.showToast({
        title: useT('复制失败'),
        icon: 'none'
      });
    }
  });
};

// 生成签名(使用HMAC-SHA256)
const generateSignature = (params, timestamp, secretKey) => {
  // 将参数按key排序后拼接
  const sortedKeys = Object.keys(params).sort();
  const paramStr = sortedKeys.map((key) => `${key}=${params[key]}`).join('&');
  // 拼接时间戳
  const signStr = `${paramStr}&timestamp=${timestamp}`;
  // 使用HMAC-SHA256生成签名
  const signature = CryptoJS.HmacSHA256(signStr, secretKey).toString();
  return signature;
};

// AES加密参数
const encryptParams = (params) => {
  // 添加时间戳(防止重放攻击)
  const timestamp = Date.now();

  // 生成签名
  const signature = generateSignature(params, timestamp, RECHARGE_CONFIG.secretKey);

  // 构建最终数据
  const data = {
    ...params,
    timestamp,
    sign: signature
  };

  // 将参数对象转换为JSON字符串
  const jsonStr = JSON.stringify(data);

  // 使用AES加密
  const encrypted = CryptoJS.AES.encrypt(jsonStr, AES_CTX.key, {
    iv: AES_CTX.iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  const cipherText = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

  // URL安全的Base64编码
  const urlSafeEncrypted = cipherText.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');

  return urlSafeEncrypted;
};

// 生成充值链接的函数
const generateRechargeLink = (amount) => {
  if (!amount || parseFloat(amount) <= 0) {
    rechargeUrl.value = '';
    return;
  }

  const amountValue = parseFloat(amount);

  // 使用默认钱包地址
  const address = RECHARGE_CONFIG.defaultAddress;

  // 使用默认用户ID
  const userId = RECHARGE_CONFIG.defaultUserId;

  // 构建参数对象
  const params = {
    address,
    amount: amountValue.toString(),
    userId: userId.toString()
  };

  // 加密参数
  const encryptedParams = encryptParams(params);

  // 生成充值链接,使用加密后的参数
  rechargeUrl.value = `${RECHARGE_CONFIG.baseUrl}?data=${encryptedParams}`;

  // 生成二维码
  generateQRCode(rechargeUrl.value);
};
</script>

<style lang="scss" scoped>
.recharge-container {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 渐变背景头部
.header-gradient {
  background: linear-gradient(135deg, #4a90e2 0%, #12c284 100%);
  padding-bottom: 24rpx;
  border-radius: 0 0 24rpx 24rpx;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -20%;
    width: 400rpx;
    height: 400rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 300rpx;
    height: 300rpx;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 50%;
  }
}

.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #fff;
}

// 金额输入卡片
.amount-card {
  margin: 0 20rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx 20rpx 16rpx;
  box-shadow: 0 6rpx 20rpx rgba(74, 144, 226, 0.12);
  position: relative;
  z-index: 1;
}

.amount-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;
  text-align: center;
}

.amount-input-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.currency-prefix {
  font-size: 32rpx;
  font-weight: 600;
  color: #12c284;
  margin-right: 10rpx;
}

.amount-input {
  font-size: 48rpx;
  font-weight: 700;
  color: #333;
  text-align: center;
  min-width: 180rpx;
  background: transparent;
}

.amount-placeholder {
  color: #d0d0d0;
}

// 快捷金额选择
.quick-amounts {
  display: flex;
  gap: 10rpx;
  justify-content: space-between;
}

.quick-amount-item {
  flex: 1;
  height: 48rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #e8f8f3 100%);
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #e0e0e0;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    background: linear-gradient(135deg, #e8f8f3 0%, #d0f0e4 100%);
    border-color: #12c284;
  }
}

.quick-amount-text {
  font-size: 24rpx;
  font-weight: 600;
  color: #12c284;
}

// 主要内容区域
.main-content {
  flex: 1;
  padding: 12rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  overflow-y: auto;
}

// 流程步骤
.steps-flow {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
  gap: 6rpx;
  flex-shrink: 0;
}

.flow-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6rpx;
}

.flow-number {
  width: 32rpx;
  height: 32rpx;
  background: linear-gradient(135deg, #4a90e2, #12c284);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18rpx;
  font-weight: 600;
  color: #fff;
  box-shadow: 0 2rpx 6rpx rgba(74, 144, 226, 0.25);
}

.flow-text {
  font-size: 20rpx;
  color: #666;
  font-weight: 500;
  white-space: nowrap;
}

.flow-arrow {
  font-size: 24rpx;
  color: #12c284;
  font-weight: 600;
  margin: 0 2rpx;
  padding-bottom: 16rpx;
}

// 充值说明卡片
.info-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 20rpx rgba(74, 144, 226, 0.08);
  border: 1rpx solid rgba(74, 144, 226, 0.1);
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-icon-wrapper {
  width: 48rpx;
  height: 48rpx;
  background: linear-gradient(135deg, #e8f4fd, #e8f8f3);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.info-icon-dot {
  width: 8rpx;
  height: 8rpx;
  background: linear-gradient(135deg, #4a90e2, #12c284);
  border-radius: 50%;
  box-shadow: 0 0 0 6rpx rgba(74, 144, 226, 0.2);
}

.info-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.info-steps {
  display: flex;
  flex-direction: column;
}

.step-item {
  display: flex;
  align-items: flex-start;
  position: relative;
}

.step-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20rpx;
  position: relative;
}

.step-dot {
  width: 16rpx;
  height: 16rpx;
  background: #e0e0e0;
  border-radius: 50%;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;

  &.active {
    width: 20rpx;
    height: 20rpx;
    background: linear-gradient(135deg, #4a90e2, #12c284);
    box-shadow: 0 0 0 6rpx rgba(74, 144, 226, 0.15);
  }
}

.step-line {
  width: 2rpx;
  height: 48rpx;
  background: linear-gradient(180deg, #e0e0e0 0%, rgba(224, 224, 224, 0.3) 100%);
  margin-top: 4rpx;
}

.step-content {
  flex: 1;
  padding: 0 0 32rpx 0;
}

.step-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

// 钱包信息卡片
.wallet-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(74, 144, 226, 0.08);
  border: 1rpx solid rgba(74, 144, 226, 0.1);
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-shrink: 0;
}

.wallet-icon-wrapper {
  width: 48rpx;
  height: 48rpx;
  background: linear-gradient(135deg, #e8f4fd, #e8f8f3);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.wallet-icon {
  width: 24rpx;
  height: 20rpx;
  background: linear-gradient(135deg, #4a90e2, #12c284);
  border-radius: 4rpx 4rpx 0 0;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    bottom: -5rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 18rpx;
    height: 5rpx;
    background: linear-gradient(135deg, #4a90e2, #12c284);
    border-radius: 0 0 2rpx 2rpx;
  }
}

.wallet-info {
  flex: 1;
}

.wallet-label {
  font-size: 20rpx;
  color: #999;
  margin-bottom: 4rpx;
  display: block;
}

.wallet-address {
  background: linear-gradient(135deg, #f8f9fa, #f0f0f0);
  border-radius: 6rpx;
  padding: 8rpx 12rpx;
  border: 1rpx solid #e0e0e0;
}

.address-text {
  font-size: 22rpx;
  font-weight: 600;
  color: #333;
  font-family: 'Courier New', monospace;
}

// 充值链接卡片
.link-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(18, 194, 132, 0.1);
  border: 1rpx solid rgba(18, 194, 132, 0.15);
  flex-shrink: 0;
}

.link-success-badge {
  display: inline-flex;
  align-items: center;
  gap: 6rpx;
  background: linear-gradient(135deg, #e8f8f3, #d0f0e4);
  padding: 6rpx 14rpx;
  border-radius: 14rpx;
  margin-bottom: 12rpx;
}

// 二维码区域
.qrcode-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12rpx 0;
  margin-bottom: 12rpx;
}

.qrcode-container {
  background: #fff;
  border-radius: 8rpx;
  padding: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.06);
  border: 2rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qrcode-canvas {
  display: block;
}

.qrcode-tip {
  font-size: 20rpx;
  color: #999;
  margin-top: 8rpx;
  text-align: center;
}

.success-icon {
  width: 18rpx;
  height: 18rpx;
  background: #12c284;
  border-radius: 50%;
  position: relative;

  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -60%) rotate(45deg);
    width: 4rpx;
    height: 7rpx;
    border-right: 2rpx solid #fff;
    border-bottom: 2rpx solid #fff;
  }
}

.success-text {
  font-size: 22rpx;
  font-weight: 600;
  color: #12c284;
}

.link-url {
  background: linear-gradient(135deg, #f8f9fa, #f0f0f0);
  border-radius: 8rpx;
  padding: 10rpx 12rpx;
  margin-bottom: 12rpx;
  border: 1rpx solid #e0e0e0;
}

.url-text {
  font-size: 20rpx;
  color: #666;
  word-break: break-all;
  line-height: 1.5;
}

.link-actions {
  display: flex;
}

.link-btn {
  width: 100%;
  height: 72rpx;
  border: none;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.2);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:active::before {
    opacity: 1;
  }

  &.copy-btn {
    background: linear-gradient(135deg, #4a90e2, #12c284);
    box-shadow: 0 4rpx 12rpx rgba(18, 194, 132, 0.3);

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(18, 194, 132, 0.3);
    }
  }
}

.btn-icon {
  width: 32rpx;
  height: 32rpx;
  position: relative;
}

.copy-icon {
  border: 2rpx solid #fff;
  border-radius: 4rpx;

  &::after {
    content: '';
    position: absolute;
    top: 4rpx;
    left: 4rpx;
    width: 100%;
    height: 100%;
    border: 2rpx solid #fff;
    border-radius: 4rpx;
    background: transparent;
  }
}

.link-btn-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}
</style>
